package com.hua.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns= {"/*"},initParams= {
		@WebInitParam(name="exclude",value="/login.jsp,/login,/noprivilige.jsp,.css,.png,.jpg,.js")//如果获取的url是这些就放行，排除这些内容
})
public class PermissionFilter implements Filter {

	public static String excludeString ; //定义一个全局对象去获取exclude
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		excludeString = filterConfig.getInitParameter("exclude");//拿到exclude的初始化值
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;//强转ServletRequest为HttpServletRequest
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;//强转ServletResponse为HttpServletResponse
		Object user = httpServletRequest.getSession().getAttribute("user");//先拿过来user信息
		String uri = httpServletRequest.getRequestURI();//获取这个URI，如果是/login.jsp,/login,/noprivilige.jsp,.css,.png,.jpg,.js 放行
		//System.out.println(uri);测试uri
		// System.out.println(httpServletRequest.getContextPath());//获取项目名,即如果是/sct/也给过，不会出现一开始404
		if(isExist(uri) || uri.equals(httpServletRequest.getContextPath()+"/")) {//以项目名为结尾的也给他过
			chain.doFilter(httpServletRequest, httpServletResponse);//如果是直接放行，否则在去判断user
		}else {
			if(user != null) {
				chain.doFilter(httpServletRequest, httpServletResponse);//如果users不为空，放行
			}else {
				httpServletResponse.sendRedirect("noprivilige.jsp");//为空跳转到没有权限的页面（重定向的方式）
			}
		}
	}
	
	public static boolean isExist(String uri) {
		//最后url的结尾与exclude匹配
		String[] arr = excludeString.split(",");//转化成数组进行比较
		boolean flag = false;//flag标识，默认返回false
		for (String string : arr) {
			if(uri.endsWith(string)) { //判断String
				flag = true;
			}
		}
		return flag;
	}


	@Override
	public void destroy() {

	}

}
